package cn.westv.scps.weather;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import cn.westv.scps.connTools.ProxyConnExec;
import cn.westv.scps.domain.AreaSeverEntity;
import cn.westv.scps.service.areaserver.IAreaServerService;
import cn.westv.scps.utils.SpringContextUtil;
import org.springframework.context.ApplicationContext;

public class WeatherTools {

	public static final String KEY = "78d9ad412c7e4cba8ddde955d7969d30";
	public static final String URL = "https://free-api.heweather.com/v5/now";
//	public static final String ICON_IMG_URL = "https://cdn.heweather.com/cond_icon/100.png";
	
//	private String Key = "78d9ad412c7e4cba8ddde955d7969d30";
//	private String url = "https://free-api.heweather.com/v5/now";

	public static Map<String, JSONObject> weatherMap = new HashMap<>();

//	public void refreshWeather() throws Exception {
//		IAreaServerService areaServerService = (IAreaServerService) SpringContextUtil.getBean("areaServerServiceImpl");
//		List<AreaSeverEntity> list = areaServerService.find("from AreaSeverEntity", AreaSeverEntity.class, null);
//		if (list != null && list.size() > 0) {
//			for (AreaSeverEntity areaSeverEntity : list) {
//				JSONObject weather = ProxyConnExec.getWeather(KEY, areaSeverEntity.getServerName(), URL);
//				weatherMap.put(areaSeverEntity.getAreaCode(), weather);
//				areaSeverEntity = null;
//			}
//		}
//		list = null;
//	}

	public void refreshWeather() throws Exception {
		String path = this.getClass().getClassLoader().getResource("/").getPath();
		path += "config/weatherarea.txt";
//		File file = new File(path);
		BufferedReader reader = null;
		String txtStr = "";
		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF-8"));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				txtStr += tempString + ";";
//				System.out.println("line " + line + ": " + tempString);
//				line++;
			}
//			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}

		String[] areas = txtStr.split(";");
		if (areas != null && areas.length > 0) {
			for (String  areaName : areas) {
				JSONObject weather = ProxyConnExec.getWeather(KEY, areaName, URL);
				weatherMap.put(areaName, weather);
			}
		}
	}

}
